import { ref } from 'vue'

export function useBagTypeCalculation() {
  const bagTypeCalculations = {
    "三边封袋": (dk, dg, cd) => ({
      area: dk * dg * 2,
      price: dk * 0.2
    }),
    "三边封中封袋": (dk, dg, cd) => ({
      area: (dk + 0.015) * dg * 2,
      price: dg * 0.2
    }),
    "自立袋": (dk, dg, cd) => {
      if (!cd) throw new Error("请输入插底参数")
      return {
        area: (dg * 2 + cd) * dk,
        price: dk * 0.2
      }
    },
    "八边封": (dk, dg, cd) => {
      if (!cd) throw new Error("请输入插底参数")
      return {
        area: (dk + cd) * 2 * (0.5 * cd + dg),
        price: dk * 1
      }
    },
    "卷膜": (dk, dg, cd) => ({
      area: dk * dk,
      price: 0
    }),
    "风琴袋": (dk, dg, cd) => {
      if (!cd) throw new Error("请输入插底参数")
      return {
        area: (dk + cd + 0.015) * 2 * dg,
        price: dg * 0.2
      }
    },
    "四边封": (dk, dg, cd) => {
      if (!cd) throw new Error("请输入插底参数")
      return {
        area: (dk + cd) * 2 * dg,
        price: dg * 0.2
      }
    },
    "中封袋": (dk, dg, cd) => ({
      area: (dk + 0.015) * 2 * (dg / 1000),
      price: dg * 0.2
    }),
    "四边封+拉链": (dk, dg, cd) => {
      if (!cd) throw new Error("请输入插底参数")
      return {
        area: (dk + cd) * 2 * dg,
        price: dk * 1
      }
    }
  }

  const zhidaiPrice = ref(0)

  const calculateBagType = (daixing, dk, dg, cd) => {
    if (!daixing) return 0
    
    const dkM = Number(dk) / 1000
    const dgM = Number(dg) / 1000
    const cdM = cd ? Number(cd) / 1000 : 0
    
    const calculation = bagTypeCalculations[daixing]
    if (!calculation) return 0
    
    try {
      const { area, price } = calculation(dkM, dgM, cdM)
      zhidaiPrice.value = price
      return truncateDecimals(area, 4)
    } catch (error) {
      console.error(error.message)
      return 0
    }
  }

  return {
    zhidaiPrice,
    calculateBagType
  }
}